<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;

/**
 * 基类表单验证
 * @package App\Http\Requests
 */
class AdminBaseRequest extends FormRequest
{
    /**
     * 重写验证响应
     * @param Validator $validator
     */
    public function failedValidation(Validator $validator)
    {
        $errors = [];
        $oriErrors = $validator->getMessageBag()->toArray();
        foreach ($oriErrors as $err){
            $errors[] = implode('、', $err);
        }
        $requestType = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] ? strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) : '';
        if ($requestType == 'xmlhttprequest') {
            exit(json_encode([
                    'status' => 'error',
                    'data' => $oriErrors,
                    'title' => '请求的数据无效',
                    'message' => implode('、', $errors),
                ]));
        } else {
            parent::failedValidation($validator);
        }
    }
}
